package com.hontech.bv.ui.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.Button
import android.widget.FrameLayout
import com.hontech.bv.R
import com.hontech.bv.conn.SerialPortMod
import com.hontech.bv.task.onClick
import com.hontech.bv.ui.window.showErr
import com.hontech.bv.utils.SERIAL_PORT_NAMES
import com.jaredrummler.materialspinner.MaterialSpinner

class SingleSerialPortView(ctx: Context, attrs: AttributeSet) : FrameLayout(ctx, attrs) {

    private val btnHide: Button
    private val btnOpen: Button
    private val spinner: MaterialSpinner

    init {
        val view = LayoutInflater.from(ctx).inflate(R.layout.view_serial_port_single, this)
        btnHide = view.findViewById(R.id.id_single_serial_port_btn_hide)
        btnOpen = view.findViewById(R.id.id_single_serial_port_btn_open)
        spinner = view.findViewById(R.id.id_single_serial_port_spinner)
        spinner.setItems(SERIAL_PORT_NAMES)

        btnHide.setOnClickListener { onClickHide() }
        show()
        btnOpen.onClick(::onClickOpen)
    }

    private fun hide() {
        btnOpen.visibility = GONE
        spinner.visibility = GONE
        btnHide.text = "显示"
    }

    private fun show() {
        btnOpen.visibility = VISIBLE
        spinner.visibility = VISIBLE
        btnHide.text = "隐藏"
    }

    private suspend fun onClickOpen() {

        if (SerialPortMod.isOpen()) {
            SerialPortMod.close()
            btnOpen.text = "打开"
            return
        }

        try {
            SerialPortMod.open( SERIAL_PORT_NAMES[spinner.selectedIndex] )
            btnOpen.text = "关闭"
        } catch (e: Exception) {
            showErr("打开失败", e)
        }
    }

    private fun onClickHide() {
        if (btnOpen.visibility == GONE) {
            show()
        } else {
            hide()
        }
    }
}
